<template>
  <div class="app-container">
    <el-tabs v-model="activeName" @tab-click="handleClick">
      <el-tab-pane v-for="type in bannerTypeOptions"
                   :label="type.dictLabel"
                   :name="type.dictValue + ''">

        <el-row :gutter="10" class="mb8">
          <el-col :span="1.5">
            <el-button type="primary" icon="el-icon-plus" size="mini" @click="handleAdd">新增</el-button>
          </el-col>
          <el-col :span="1.5">
            <el-button type="danger" icon="el-icon-delete" size="mini" :disabled="multiple" @click="handleDelete">删除</el-button>
          </el-col>
          <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
        </el-row>

        <el-table v-loading="loading" :data="bannerList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" />
          <el-table-column label="链接类型" align="center" prop="linkTypeName" />
          <el-table-column label="链接地址" align="center" prop="linkUrl" />
          <el-table-column label="状态" align="center">
            <template slot-scope="scope">
              <div>
                <el-tag v-if="scope.row.state === 0" style="cursor: pointer" :type="''">显示</el-tag>
                <el-tag v-else style="cursor: pointer" :type=" 'info' ">停用</el-tag>
              </div>
            </template>
          </el-table-column>
          <el-table-column label="图片" align="center">
            <template slot-scope="scope">
              <a :href="scope.row.imgPath" style="color: #42b983" target="_blank">
                <img :src="scope.row.imgPath" title="点击打开" class="el-avatar" style="width: 100px;height: 60px;">
              </a>
            </template>
          </el-table-column>
          <el-table-column label="排序" align="center" prop="sort" />
          <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
            <template slot-scope="scope">
              <el-button size="mini" type="text" icon="el-icon-edit" @click="handleUpdate(scope.row)"
                         v-hasPermi="['module:banner:edit']">修改</el-button>
              <el-button size="mini" type="text" icon="el-icon-delete" @click="handleDelete(scope.row)"
                         v-hasPermi="['module:banner:remove']">删除</el-button>
            </template>
          </el-table-column>
        </el-table>

        <pagination v-show="total > 0"
                    :total="total"
                    :page.sync="queryParams.pageNum"
                    :limit.sync="queryParams.pageSize"
                    @pagination="getList"/>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加或修改轮播图（广告）对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="550px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
        <el-form-item label="轮播类型" prop="adType">
          <el-select v-model="form.adType" placeholder="请选择轮播类型" style="width:100%;" size="mini">
            <el-option v-for="dict in bannerTypeOptions"
                       :key="dict.dictValue"
                       :label="dict.dictLabel"
                       :value="parseInt(dict.dictValue)"/>
          </el-select>
        </el-form-item>
        <el-form-item label="链接类型" prop="linkType">
          <el-select v-model="form.linkType" placeholder="请选择链接类型" size="mini" style="width:100%;">
            <el-option v-for="dict in linkTypeOptions"
                       :key="dict.dictValue"
                       :label="dict.dictLabel"
                       :value="dict.dictValue"/>
          </el-select>
        </el-form-item>
        <el-form-item label="商家名称" prop="linkKey" v-if="form.linkType === 'mer'">
          <el-select v-model="form.linkKey" placeholder="请选择商家名称" size="mini" style="width:100%;">
            <el-option v-for="mer in merList"
                       :key="mer.id"
                       :label="mer.shopName"
                       :value="mer.id"/>
          </el-select>
        </el-form-item>
        <el-form-item label="通知公告" prop="linkKey" v-if="form.linkType === 'notice'">
          <el-select v-model="form.linkKey" placeholder="请选择商家名称"  size="mini" style="width:100%;">
            <el-option v-for="notice in noticeList"
                       :key="notice.noticeId"
                       :label="notice.noticeTitle"
                       :value="notice.noticeId">
              <span style="float: left">{{ notice.noticeTitle }}</span>
              <span style="float: right; color: #8492a6; font-size: 13px" v-if="notice.noticeType === '1'">通知</span>
              <span style="float: right; color: #8492a6; font-size: 13px" v-if="notice.noticeType === '2'">公告</span>
              <span style="float: right; color: #8492a6; font-size: 13px" v-if="notice.noticeType === '3'">公共收益工示</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="链接地址" prop="linkUrl">
          <el-input v-model="form.linkUrl" placeholder="请输入链接地址" size="mini"/>
        </el-form-item>
        <el-form-item prop="imgUrl" label="图片">
          <single-pic v-model="form.imgPath" type="image" @handleChecked="chooseImg" :uploadType="6"
                      :num="1" :width="220" :height="150" />
        </el-form-item>
        <el-form-item label="状态" prop="state">
          <el-radio-group v-model="form.state" size="mini">
            <el-radio :value="0" :label="0">正常</el-radio>
            <el-radio :value="1" :label="1">停用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="排序索引" prop="sort">
          <el-input v-model="form.sort" type="number" placeholder="请输入排序索引" size="mini"/>
        </el-form-item>
        <!--        <el-form-item label="广告内容" prop="content">-->
        <!--          <editor v-model="form.content" :min-height="192"/>-->
        <!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button :loading="buttonLoading" size="mini" type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel" size="mini">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
  import { listBanner, getBanner, delBanner, addBanner, updateBanner } from "@/api/module/banner";
  import {listNotices,} from "@/api/system/notice";

  import { listMer} from "@/api/module/mer/mer";

  import singlePic from '@/components/SingleMaterial'
  import editor from '@/components/Editor';

  export default {
    name: "Banner",
    components: { singlePic, editor},
    data() {
      return {
        activeName:'1',
        // 按钮loading
        buttonLoading: false,
        // 遮罩层
        loading: true,
        // 导出遮罩层
        exportLoading: false,
        // 选中数组
        ids: [],
        // 非单个禁用
        single: true,
        // 非多个禁用
        multiple: true,
        // 显示搜索条件
        showSearch: true,
        // 总条数
        total: 0,
        // 轮播图（广告）表格数据
        bannerList: [],
        merList:[],
        // 弹出层标题
        title: "",
        // 是否显示弹出层
        open: false,
        bannerTypeOptions:[],
        linkTypeOptions:[],
        // 公告表格数据
        noticeList: [],
        // 状态数据字典
        statusOptions: [],
        // 查询参数
        queryParams: {
          pageNum: 1,
          pageSize: 10,
          adType:undefined,
        },
        // 查询参数
        queryParamsMer: {
          pageNum: 1,
          pageSize: 100,
          isShowProduct:0,
        },
        // 查询参数
        queryParamsNotice: {
          pageNum: 1,
          pageSize: 10,
          noticeType: undefined,
        },
        // 表单参数
        form: {},
        // 表单校验
        rules: {
        }
      };
    },
    created() {
      this.getDicts("banner_type").then(response => {
        this.bannerTypeOptions = response.data;
        this.queryParams.adType = parseInt(this.bannerTypeOptions[0].dictValue);
        this.getList();
      });
      this.getDicts("link_type").then(response => {
        this.linkTypeOptions = response.data;
      });
      this.getDicts("sys_normal_disable").then(response => {
        this.statusOptions = response.data;
      });
      this.getMerList();
      this.getNoticeList()
    },
    methods: {
      /** 查询轮播图（广告）列表 */
      getList() {
        this.loading = true;
        listBanner(this.queryParams).then(response => {
          this.bannerList = response.rows;
          this.total = response.total;
          this.loading = false;
        });
      },
      getNoticeList() {
        listNotices(this.queryParamsNotice).then(response => {
          this.noticeList = response;
        });
      },
      getMerList() {
        listMer(this.queryParamsMer).then(response => {
          this.merList = response.rows;
        });
      },
      handleClick(val){
        console.log('handleClick',val);
        this.activeName = val.name;
        this.queryParams.pageNum = 1;
        this.queryParams.adType = parseInt(val.name);
        this.getList();
      },
      chooseImg(data){
        console.log("banner chooseImg",data);
        if(data.length > 0) {
          console.log("banner imgPath",data[0].imgUrl);
          console.log("banner url",data[0].url);
          this.form.imgPath = data[0].imgUrl;
          this.form.imgUrl = data[0].url;
        }
      },
      // 取消按钮
      cancel() {
        this.open = false;
        this.reset();
      },
      // 表单重置
      reset() {
        this.form = {
          id: undefined,
          adType: undefined,
          imgUrl: undefined,
          linkType: undefined,
          linkKey: undefined,
          linkUrl: undefined,
          state: undefined,
          sort: undefined,
          content:undefined,
        };
        this.resetForm("form");
      },
      /** 搜索按钮操作 */
      handleQuery() {
        this.queryParams.pageNum = 1;
        this.getList();
      },
      /** 重置按钮操作 */
      resetQuery() {
        this.resetForm("queryForm");
        this.handleQuery();
      },
      // 多选框选中数据
      handleSelectionChange(selection) {
        this.ids = selection.map(item => item.id);
        this.single = selection.length!==1;
        this.multiple = !selection.length;
      },
      /** 新增按钮操作 */
      handleAdd() {
        this.reset();
        this.open = true;
        this.title = "添加轮播图（广告）";
      },
      /** 修改按钮操作 */
      handleUpdate(row) {
        this.loading = true;
        this.reset();
        const id = row.id || this.ids;
        getBanner(id).then(response => {
          this.loading = false;
          this.form = response.data;
          this.open = true;
          this.title = "修改轮播图（广告）";
        });
      },
      /** 提交按钮 */
      submitForm() {
        this.$refs["form"].validate(valid => {
          if (valid) {
            this.buttonLoading = true;
            if (this.form.id != null) {
              updateBanner(this.form).then(response => {
                this.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            } else {
              addBanner(this.form).then(response => {
                this.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              }).finally(() => {
                this.buttonLoading = false;
              });
            }
          }
        });
      },
      uploadCallBack(data){
        console.log('uploadCallBack',data);
        if(data.type === 'upload'){
          this.form.imgUrl = data.imgUrl.name;
        }else if(data.type === 'remove'){

        }
      },
      /** 删除按钮操作 */
      handleDelete(row) {
        const ids = row.id || this.ids;
        this.$confirm('是否确认删除轮播图（广告）编号为"' + ids + '"的数据项?', "警告", {
          confirmButtonText: "确定",
          cancelButtonText: "取消",
          type: "warning"
        }).then(() => {
          this.loading = true;
          return delBanner(ids);
        }).then(() => {
          this.loading = false;
          this.getList();
          this.msgSuccess("删除成功");
        }).catch(() => {});
      },
    }
  };
</script>
